package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeJSONArrayEntity;
import com.cci.kangdao.dao.CampaignTaskFlowDao;
import com.cci.kangdao.dao.CampaignTaskInfoDao;
import com.cci.kangdao.dao.CampaignTaskSyncDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.request.SaveCampaignTaskRequest;
import com.cci.kangdao.entity.CampaignTaskFlow;
import com.cci.kangdao.service.CampaignTaskInfoService;
import com.cci.kangdao.utilTool.*;
import com.gexin.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linjiankun
 * @date 2023/10/23 15:57
 */
@Service("CampaignTaskInfoService")
public class CampaignTaskInfoServiceImpl implements CampaignTaskInfoService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private CampaignTaskInfoDao campaignTaskInfoDao;
    @Resource
    private CampaignTaskFlowDao campaignTaskFlowDao;
    @Resource
    private CampaignTaskSyncDao campaignTaskSyncDao;

    /**
     * 通过工单编号获取campaign任务列表
     * @param map
     * @return
     */
    public ModelAndView getCampaignTaskList(Map map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        // 1.数据校验
        String orderNo = MapUtils.getString(map, "workOrderNo", "");
        if (StringUtils.isEmpty(orderNo)) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }
        Map<String, Object> data = new HashMap<>();
        CRMResponeJSONArrayEntity crmResponse = CRMApiUtils.getCRMServiceApi().checkCampaignTask(map);
        if (crmResponse.getStatus() != 0) {
            log.error("获取crm系统campaign任务列表失败，状态：" + crmResponse.getStatus() + "，用户信息:" + crmResponse.getMessage());
            data.put("sfResult", "不存在");
        } else {
                    /*{
                        "status": "0",
                        "message": "success",
                        "result": "存在 / 不存在",
                        "data": [{
                        "trpName": "任务名称1",
                        "trpDescription": "任务描述1",
                        "trpCode": "任务code1",
                        "campaignRangeId": "任务范围1",
                        "esn": "11111111",
                        "gsn": "22222222"
                    }]
                    }*/
            JSONArray  jsonArray = new JSONArray();
            if (crmResponse.getData()!= null && crmResponse.getData().size()>0) {
                for (Object datum : crmResponse.getData()) {
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(com.alibaba.fastjson.JSON.toJSONString(datum));
//                    jsonObject.put("trpFile","https://cummins-cn--full.sandbox.my.salesforce.com/sfc/p/VE000001EQ25/a/VE00000058cr/cpeC8dFUCHTKJDhuqLcC.HG_O63yAbsEdZD_5hvNbc4-title:66667;https://cummins-cn--full.sandbox.my.salesforce.com/sfc/p/VE000001EQ25/a/VE00000058cr/cpeC8dFUCHTKJDhuqLcC.HG_O63yAbsEdZD_5hvNbc4-title:66667");
                    log.error("获取crm系统campaign任务列表"+jsonObject.toString());
                    List<Map<String,String>> listvo = new ArrayList<>();
                    if (StringUtils.isNotBlank(jsonObject.getString("trpFile"))) {
                        String[] trpFiles = jsonObject.getString("trpFile").split(";");
                        if (trpFiles!=null && trpFiles.length>0) {
                            for (String trpFile : trpFiles) {
                                Map<String,String> mapvo = new HashMap<>();
                                String substringStart = trpFile.substring(0,trpFile.indexOf("-title:"));
                                String substringEnd = trpFile.substring(trpFile.indexOf("-title:")+7,trpFile.length());
                                mapvo.put("title",substringEnd);
                                mapvo.put("url",substringStart);
                                listvo.add(mapvo);
                            }
                        }
                        jsonObject.put("trpFileList",listvo);
                    }
                    jsonArray.add(jsonObject);
                }
            }
            data.put("sfResult", crmResponse.getResult());
            data.put("campaignTaskList", jsonArray);
        }
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    //站长保存campaign任务信息
    @Transactional
    public ModelAndView saveCampaignTask(String paramStr, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        log.info("saveCampaignTask.aspx接口入参paramStr："+paramStr);
        //1.提取参数信息
        SaveCampaignTaskRequest saveCampaignTaskRequest = JSON.parseObject(paramStr, SaveCampaignTaskRequest.class);
        //2.校验参数是否必填
        Long orderId = saveCampaignTaskRequest.getOrderId();
        String orderNo = saveCampaignTaskRequest.getWorkOrderNo();
        List<SaveCampaignTaskRequest.CampaignTask> campaignTasks = saveCampaignTaskRequest.getCampaignTaskListList();
        if(null == orderId || StringUtils.isEmpty(orderNo) || CollectionUtils.isEmpty(campaignTasks)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        //校验的同时  拼接sf所需字段
        List<Map<String,Object>> sfDataList = new ArrayList<>();
        for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
            String trpName = campaignTask.getTrpName();
            String trpDescription = campaignTask.getTrpDescription();
            String trpCode = campaignTask.getTrpCode();
            String campaignRangeId = campaignTask.getCampaignRangeId();
            String esn = campaignTask.getEsn();
            String gsn = campaignTask.getGsn();
            Integer campaignTaskStatus = campaignTask.getCampaignTaskStatus();
            Integer refusalReasonValue = campaignTask.getRefusalReasonValue();
            String refusalOtherReason = campaignTask.getRefusalOtherReason();
            if(StringUtils.isEmpty(trpName) || StringUtils.isEmpty(trpDescription)
             || StringUtils.isEmpty(trpCode) || StringUtils.isEmpty(campaignRangeId) || null == campaignTaskStatus
             || (StringUtils.isEmpty(esn) && StringUtils.isEmpty(gsn) ||
             (campaignTaskStatus == 2 && (null == refusalReasonValue || StringUtils.isEmpty(refusalOtherReason))))){
                ParameterTool.writeResponse(response, 17,"缺少必要参数！");
                return null;
            }
            //sf所需对象
            Map<String,Object> sfData = new HashMap<>();
            sfData.put("campaignRangeId",campaignRangeId);
            sfData.put("status",campaignTaskStatus == 1?"认领":"拒绝");
            sfData.put("refuseReason",refusalOtherReason);
            sfData.put("campaignTaskId","");
            sfDataList.add(sfData);
        }
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        int num = campaignTaskInfoDao.insertBatch(orderId,campaignTasks,userT.getId(),currentTime);
        try {
            Map<String,Object> sfMap = new HashMap<>();
            sfMap.put("workOrderNo",orderNo);
            sfMap.put("source","经销商");
            sfMap.put("data",sfDataList);
            CRMResponeJSONArrayEntity crmResponse = CRMApiUtils.getCRMServiceApi().syncDealerCampaignOptionToSF(sfMap);
            if(crmResponse.getStatus()!=0) {
                log.error("dbu同步campaign任务状态失败，状态："+crmResponse.getStatus()+"，用户信息:"+crmResponse.getMessage());
                //站长接受或拒绝任务，技师接受任务同步到crm失败报错话术
                ParameterTool.writeResponse(response, SMSEnum.type63.getIndex(),SMSEnum.type63.getName());
                return null;
            }else{
                /*{
                    "status": "0",
                        "message": "success",
                        "data": [{
                    "isExpired": "no",
                            "campaignTaskIdOld": "",
                            "campaignTaskIdNew": "task111",
                            "campaignRangeId": "111"
                }, {
                    "isExpired": "yes",
                            "campaignTaskIdOld": "",
                            "campaignTaskIdNew": "",
                            "campaignRangeId": "222"
                }]
                }*/
                JSONArray jsonArray = crmResponse.getData();
                if(CollectionUtils.isNotEmpty(jsonArray)){
                    for (Object object : jsonArray) {
                        JSONObject jsonObject = JSONObject.fromObject(object);
                        String isExpired = jsonObject.getString("isExpired");
                        String campaignRangeId = jsonObject.getString("campaignRangeId");
                        if("yes".equals(isExpired)){  //如果过期  需要将对应的campaign任务的flag置为-1
                            campaignTaskInfoDao.delTaskByOrderIdRangeId(orderId,campaignRangeId,userT.getId(),currentTime);
                        }else{
                            String campaignTaskIdNew = jsonObject.getString("campaignTaskIdNew");
                            Map<String,Object> campaignTaskInfoMap = new HashMap<>();
                            campaignTaskInfoMap.put("newCampaignTaskId",campaignTaskIdNew);
                            campaignTaskInfoMap.put("workOrderId",orderId);
                            campaignTaskInfoMap.put("campaignRangeId",campaignRangeId);
                            campaignTaskInfoMap.put("updator",userT.getId());
                            campaignTaskInfoMap.put("updateTime",currentTime);
                            campaignTaskInfoDao.updateCampaignTaskInfo(campaignTaskInfoMap);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("dbu同步campaign任务状态失败，异常信息："+e.getMessage(),e);
            //站长接受或拒绝任务，技师接受任务同步到crm失败报错话术
            ParameterTool.writeResponse(response, SMSEnum.type63.getIndex(),SMSEnum.type63.getName());
            return null;
        }
        ParameterTool.writeSuccessResponse(response,num);
        return null;
    }



    /**
     * 通过工单id获取campaign任务列表详情
     * @param map
     * @return
     */
    public ModelAndView getCampaignTaskListByOrderId(Map map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            // 1.数据校验
            Long workOrderId = MapUtils.getLongValue(map,"workOrderId",-1);
            if (workOrderId == -1) {
                ParameterTool.writeErrorResponse(response, -5);
                return null;
            }
            Map<String, Object> data = new HashMap<>();
            List<Map<String,Object>> campaignList = campaignTaskInfoDao.getCampaignListByOrderId(workOrderId);
            if (CollectionUtils.isNotEmpty(campaignList)) {
                for (Map<String, Object> stringObjectMap : campaignList) {
                    List<Map<String,String>> listvo = new ArrayList<>();
                    if (StringUtils.isNotBlank(MapUtils.getString(stringObjectMap,"trpFile"))) {
                        String[] trpFiles = MapUtils.getString(stringObjectMap,"trpFile").split(";");
                        if (trpFiles!=null && trpFiles.length>0) {
                            for (String trpFile : trpFiles) {
                                Map<String,String> mapvo = new HashMap<>();
                                String substringStart = trpFile.substring(0,trpFile.indexOf("-title:"));
                                String substringEnd = trpFile.substring(trpFile.indexOf("-title:")+7,trpFile.length());
                                mapvo.put("title",substringEnd);
                                mapvo.put("url",substringStart);
                                listvo.add(mapvo);
                            }
                        }
                        stringObjectMap.put("trpFileList",listvo);
                    }
                }
            }
            data.put("campaignTaskList",campaignList);
            ParameterTool.writeSuccessResponse(response,data);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }




    //技师主动接受campaign任务信息
    @Transactional
    public ModelAndView acceptCampaignTask(String paramStr, HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
        log.info("acceptCampaignTask.aspx接口入参paramStr："+paramStr);
        //1.提取参数信息
        SaveCampaignTaskRequest saveCampaignTaskRequest = JSON.parseObject(paramStr, SaveCampaignTaskRequest.class);
        //2.校验参数是否必填
        Long orderId = saveCampaignTaskRequest.getOrderId();
        String orderNo = saveCampaignTaskRequest.getWorkOrderNo();
        List<SaveCampaignTaskRequest.CampaignTask> campaignTasks = saveCampaignTaskRequest.getCampaignTaskListList();
        if(null == orderId || StringUtils.isEmpty(orderNo) || CollectionUtils.isEmpty(campaignTasks)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        //校验的同时  拼接sf所需字段
        List<Map<String,Object>> sfDataList = new ArrayList<>();
        for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
            Long id = campaignTask.getId();
            String campaignRangeId = campaignTask.getCampaignRangeId();
            Integer campaignTaskStatus = campaignTask.getCampaignTaskStatus();
            String newCampaignTaskId = campaignTask.getNewCampaignTaskId();
            String trpName = campaignTask.getTrpName();
            String trpDescription = campaignTask.getTrpDescription();
            String trpCode = campaignTask.getTrpCode();
            if(null == id || StringUtils.isEmpty(trpName) || StringUtils.isEmpty(trpDescription) || StringUtils.isEmpty(trpCode) ||
                    StringUtils.isEmpty(campaignRangeId) || null == campaignTaskStatus || StringUtils.isEmpty(newCampaignTaskId)){
                ParameterTool.writeResponse(response, 17,"缺少必要参数！");
                return null;
            }
            //sf所需对象
            Map<String,Object> sfData = new HashMap<>();
            sfData.put("campaignRangeId",campaignRangeId);
            sfData.put("status",campaignTaskStatus == 1?"认领":"拒绝");
            sfData.put("campaignTaskId",newCampaignTaskId);
            sfDataList.add(sfData);
        }
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        //存放过期得任务   返给前端报错使用
        List<Map<String,Object>> expiredCampaignTaskList = new ArrayList<>();
        //同步crm
        try {
            Map<String,Object> sfMap = new HashMap<>();
            sfMap.put("workOrderNo",orderNo);
            sfMap.put("source","技师");
            sfMap.put("data",sfDataList);
            CRMResponeJSONArrayEntity crmResponse = CRMApiUtils.getCRMServiceApi().syncDealerCampaignOptionToSF(sfMap);
            if(crmResponse.getStatus()!=0) {
                log.error("dbu技师同步campaign任务状态失败，状态："+crmResponse.getStatus()+"，用户信息:"+crmResponse.getMessage());
                //站长接受或拒绝任务，技师接受任务同步到crm失败报错话术
                ParameterTool.writeResponse(response, SMSEnum.type63.getIndex(),SMSEnum.type63.getName());
                return null;
            }else{
                /*{
                    "status": "0",
                        "message": "success",
                        "data": [{
                    "isExpired": "no",
                            "campaignTaskIdOld": "",
                            "campaignTaskIdNew": "task111",
                            "campaignRangeId": "111"
                }, {
                    "isExpired": "yes",
                            "campaignTaskIdOld": "",
                            "campaignTaskIdNew": "",
                            "campaignRangeId": "222"
                }]
                }*/
                JSONArray jsonArray = crmResponse.getData();
                if(CollectionUtils.isNotEmpty(jsonArray)){
                    for (Object object : jsonArray) {
                        JSONObject jsonObject = JSONObject.fromObject(object);
                        String isExpired = jsonObject.getString("isExpired");
                        String campaignRangeId = jsonObject.getString("campaignRangeId");
                        String campaignTaskIdOld = jsonObject.getString("campaignTaskIdOld");
                        String campaignTaskIdNew = jsonObject.getString("campaignTaskIdNew");
                        if("yes".equals(isExpired)){   //如果过期，将过期得任务信息返给前端
                            for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
                                Map<String,Object> expiredCampaignTask = new HashMap<>();
                                expiredCampaignTask.put("trpName",campaignTask.getTrpName());
                                expiredCampaignTask.put("trpDescription",campaignTask.getTrpDescription());
                                expiredCampaignTask.put("trpCode",campaignTask.getTrpCode());
                                if(campaignRangeId.equals(campaignTask.getCampaignRangeId())){
                                    expiredCampaignTaskList.add(expiredCampaignTask);
                                    break;
                                }
                            }

                        }else{   //未过期
                            //更新数据库
                            for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
                                Map<String,Object> updateMap = new HashMap<>();
                                updateMap.put("updator",userT.getId());
                                updateMap.put("updateTime",currentTime);
                                updateMap.put("campaignTaskStatus",campaignTask.getCampaignTaskStatus());
                                updateMap.put("workOrderId",orderId);
                                updateMap.put("campaignRangeId",campaignTask.getCampaignRangeId());
                                if(campaignRangeId.equals(campaignTask.getCampaignRangeId())){
                                    updateMap.put("newCampaignTaskId",campaignTaskIdNew);
                                    updateMap.put("oldCampaignTaskId",campaignTaskIdOld);
                                    campaignTaskInfoDao.updateCampaignTaskInfo(updateMap);
                                    break;
                                }
                            }
                        }
                    }
                }
                //插入操作记录表
                for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
                    CampaignTaskFlow campaignTaskFlow = new CampaignTaskFlow();
                    campaignTaskFlow.setCampaignTaskInfoId(campaignTask.getId());
                    campaignTaskFlow.setCampaignTaskStatus(campaignTask.getCampaignTaskStatus());
                    campaignTaskFlow.setRemark("技师主动接受campaign任务");
                    campaignTaskFlowDao.insert(campaignTaskFlow,userT.getId(),currentTime);
                }
            }
        } catch (Exception e) {
            log.error("dbu技师同步campaign任务状态失败，异常信息："+e.getMessage(),e);
            //站长接受或拒绝任务，技师接受任务同步到crm失败报错话术
            ParameterTool.writeResponse(response, SMSEnum.type63.getIndex(),SMSEnum.type63.getName());
            return null;
        }
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("expiredCampaignTaskList",expiredCampaignTaskList);
        ParameterTool.writeSuccessResponse(response,returnMap);
        return null;
    }



    //技师标记campaign任务状态
    @Transactional
    public ModelAndView tagCampaignTask(String paramStr, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        log.info("tagCampaignTask.aspx接口入参paramStr："+paramStr);
        //1.提取参数信息
        SaveCampaignTaskRequest saveCampaignTaskRequest = JSON.parseObject(paramStr, SaveCampaignTaskRequest.class);
        List<SaveCampaignTaskRequest.CampaignTask> campaignTasks = saveCampaignTaskRequest.getCampaignTaskListList();
        if(CollectionUtils.isEmpty(campaignTasks)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        //校验参数
        for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
            UserT userT = UserThreadLocal.get();
            String currentTime = LocalTimeUtil.getRealCurrentTime();
            Integer campaignTaskStatus = campaignTask.getCampaignTaskStatus();
            Long id = campaignTask.getId();
            if(null == campaignTaskStatus || null == id || (campaignTaskStatus != 3 && campaignTaskStatus != 4)){
                ParameterTool.writeResponse(response, 17,"缺少必要参数或所传参数非枚举值！");
                return null;
            }
            Map<String,Object> updateMap = new HashMap<>();
            updateMap.put("updator",userT.getId());
            updateMap.put("updateTime",currentTime);
            updateMap.put("campaignTaskStatus",campaignTask.getCampaignTaskStatus());
            updateMap.put("id",id);
            campaignTaskInfoDao.updateInfo(updateMap);
            CampaignTaskFlow campaignTaskFlow = new CampaignTaskFlow();
            campaignTaskFlow.setCampaignTaskInfoId(id);
            campaignTaskFlow.setCampaignTaskStatus(campaignTask.getCampaignTaskStatus());
            campaignTaskFlow.setRemark("技师标记任务状态（完成，未完成）");
            campaignTaskFlowDao.insert(campaignTaskFlow,userT.getId(),currentTime);
        }
        ParameterTool.writeSuccessResponse(response);
        return null;
    }



    //技师维修完成campaign任务并同步到crm
    @Transactional
    public ModelAndView repairFinishCampaignTask(String paramStr, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        log.info("repairFinishCampaignTask.aspx接口入参paramStr："+paramStr);
        //1.提取参数信息
        SaveCampaignTaskRequest saveCampaignTaskRequest = JSON.parseObject(paramStr, SaveCampaignTaskRequest.class);
        //2.校验参数是否必填
        Long orderId = saveCampaignTaskRequest.getOrderId();
        String orderNo = saveCampaignTaskRequest.getWorkOrderNo();
        List<SaveCampaignTaskRequest.CampaignTask> campaignTasks = saveCampaignTaskRequest.getCampaignTaskListList();
        if(null == orderId || StringUtils.isEmpty(orderNo) || CollectionUtils.isEmpty(campaignTasks)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        //校验的同时  拼接sf所需字段
        List<Map<String,Object>> sfDataList = new ArrayList<>();
        for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
            Long id = campaignTask.getId();
            String campaignRangeId = campaignTask.getCampaignRangeId();
            Integer campaignTaskStatus = campaignTask.getCampaignTaskStatus();
            String newCampaignTaskId = campaignTask.getNewCampaignTaskId();
            Integer unfinishedReasonValue = campaignTask.getUnfinishedReasonValue();
            String unfinishedOtherReason = campaignTask.getUnfinishedOtherReason();
            if(null == id || StringUtils.isEmpty(campaignRangeId) || null == campaignTaskStatus || StringUtils.isEmpty(newCampaignTaskId) ||
            (campaignTaskStatus == 4 && (null == unfinishedReasonValue || StringUtils.isEmpty(unfinishedOtherReason)))){
                ParameterTool.writeResponse(response, 17,"缺少必要参数！");
                return null;
            }
            //sf所需对象
            Map<String,Object> sfData = new HashMap<>();
            sfData.put("campaignTaskId",newCampaignTaskId);
            sfData.put("status",campaignTaskStatus == 3?"已完成":"未完成");
            if(campaignTaskStatus ==  4){
                sfData.put("notCompleteReason",unfinishedOtherReason);
            }
            sfDataList.add(sfData);
        }
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        for(SaveCampaignTaskRequest.CampaignTask campaignTask : campaignTasks){
            Map<String,Object> updateMap = new HashMap<>();
            updateMap.put("updator",userT.getId());
            updateMap.put("updateTime",currentTime);
            updateMap.put("campaignTaskStatus",campaignTask.getCampaignTaskStatus());
            if(campaignTask.getCampaignTaskStatus() == 4){
                updateMap.put("unfinishedReasonValue",campaignTask.getUnfinishedReasonValue());
                updateMap.put("unfinishedOtherReason",campaignTask.getUnfinishedOtherReason());
            }
            updateMap.put("id",campaignTask.getId());
            updateMap.put("isSubmitRepairFinish",1);
            campaignTaskInfoDao.updateInfo(updateMap);
            //插入操作记录表
            CampaignTaskFlow campaignTaskFlow = new CampaignTaskFlow();
            campaignTaskFlow.setCampaignTaskInfoId(campaignTask.getId());
            campaignTaskFlow.setCampaignTaskStatus(campaignTask.getCampaignTaskStatus());
            campaignTaskFlow.setRemark("技师维修完成campaign任务");
            campaignTaskFlowDao.insert(campaignTaskFlow,userT.getId(),currentTime);
        }

        //同步crm
        //同步crm是否成功
        int isSyncSuccess = 1;
        //失败原因
        String syncFailReason = "";
        Map<String,Object> sfMap = new HashMap<>();
        try {
            sfMap.put("workOrderNo",orderNo);
            sfMap.put("data",sfDataList);
            CRMResponeJSONArrayEntity crmResponse = CRMApiUtils.getCRMServiceApi().syncDealerCampaignStatusToSF(sfMap);
            if(crmResponse.getStatus()!=0) {
                log.error("dbu技师同步campaign任务维修完成失败，状态："+crmResponse.getStatus()+"，用户信息:"+crmResponse.getMessage());
                isSyncSuccess = 0;
                syncFailReason = crmResponse.getMessage();
            }
        } catch (Exception e) {
            log.error("dbu技师同步campaign任务状态失败，异常信息："+e.getMessage(),e);
            if(isSyncSuccess == 1){
                isSyncSuccess = 0;
                syncFailReason = e.getMessage();
            }
        }
        //同步失败
        if(isSyncSuccess == 0){
            insertCampaignTaskSync(orderId,orderNo,"DBU",MapStringConvert.mapToString(sfMap),-1,syncFailReason,1,"syncDealerCampaignStatusToSF");
        }
        ParameterTool.writeSuccessResponse(response,1);
        return null;
    }


    //同步crm失败的保存到重传表等待重传  插入公共方法
    public void insertCampaignTaskSync(Long orderId,String orderNo,String channelName,String syncData,int syncStatus,
                                       String failReason,int syncCount,String channelHost){

        Map<String,Object> insertMap = new HashMap<>();
        insertMap.put("orderId",orderId);
        insertMap.put("orderNo",orderNo);
        insertMap.put("channelName",channelName);
        insertMap.put("syncData",syncData);
        insertMap.put("syncStatus",syncStatus);
        insertMap.put("failReason",failReason);
        insertMap.put("syncCount",syncCount);
        insertMap.put("channelHost",channelHost);
        insertMap.put("userId",UserThreadLocal.get().getId());
        insertMap.put("createTime",LocalTimeUtil.getRealCurrentTime());
        campaignTaskSyncDao.insert(insertMap);
    }

}
